<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <title th:text="${vo.template.pageTitle}"></title>
    <script src="//source.szmengqukj.com/page/js/jquery-1.7.2.min.js"></script>
    <script src="//s-sdk.szmengqukj.com/cdn-boot/swiper-bundle.min.js"></script>
    <link
      rel="stylesheet"
      href="//source.szmengqukj.com/page/css/loadPage.css"
    />
    <link
      rel="stylesheet"
      href="//s-sdk.szmengqukj.com/cdn-boot/swiper-bundle.min.css"
    />
    <link
      rel="stylesheet"
      href="//s-sdk.szmengqukj.com/web/squeeze/style/animate.min.css"
    />
    <link
      rel="stylesheet"
      href="//s-sdk.szmengqukj.com/web/squeeze/style/sudoku-new-popup.css"
    />
  </head>

  <script>
    (function flexible(window, document) {
      var docEl = document.documentElement;
      var dpr = window.devicePixelRatio || 1; // 像素比，即当前设置下物理像素与css像素的比值

      // adjust body font size
      function setBodyFontSize() {
        if (document.body) {
          document.body.style.fontSize = 12 * dpr + "px";
        } else {
          document.addEventListener("DOMContentLoaded", setBodyFontSize);
        }
      }

      setBodyFontSize();

      // set 1rem = viewWidth / 10
      function setRemUnit() {
        var rem = docEl.clientWidth / 10;
        docEl.style.fontSize = rem + "px";
      }

      setRemUnit();

      // reset rem unit on page resize
      window.addEventListener("resize", setRemUnit);
      window.addEventListener("pageshow", function (e) {
        if (e.persisted) {
          setRemUnit();
        }
      });

      // detect 0.5px supports
      if (dpr >= 2) {
        var fakeBody = document.createElement("body");
        var testElement = document.createElement("div");
        testElement.style.border = ".5px solid transparent";
        fakeBody.appendChild(testElement);
        docEl.appendChild(fakeBody);
        if (testElement.offsetHeight === 1) {
          docEl.classList.add("hairlines");
        }
        docEl.removeChild(fakeBody);
      }
    })(window, document);
  </script>

  <body>
    <div class="container">
      <div class="upper-box">
        <!-- 顶部六要素 -->
        <div class="lysTop">
          <p style="text-align: center; color: white">
            <span id="developer-span" class="developer-span"></span>
            <span class="developer-span">&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <a
              id="app-auth-span"
              class="app-auth-span"
              style="color: white; text-decoration: none"
            >
              应用权限
            </a>
            <span class="app-auth-span">&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <a
              id="privacy-span"
              class="privacy-span"
              style="color: white; text-decoration: none"
            >
              隐私政策
            </a>
          </p>
          <p style="text-align: center; color: white">
            <a
              id="app-name-span"
              class="app-name-span"
              href="javascript:;"
              style="color: white; text-decoration: none"
            >
            </a>
            <span class="app-name-span">&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <a
              id="app-version-span"
              class="app-version-span"
              href="javascript:;"
              style="color: white; text-decoration: none"
            >
            </a>
            <span class="app-version-span">&nbsp;&nbsp;&nbsp;&nbsp;</span>
            <a
              id="app-time-span"
              class="app-time-span"
              href="javascript:;"
              style="color: white; text-decoration: none"
            >
            </a>
          </p>
        </div>

        <!-- 轮播内容 -->
        <div class="swiper-box">
          <div class="swiper mySwiper swiper-no-swiping">
            <div id="swiper-item" class="swiper-wrapper"></div>
          </div>
        </div>

        <!-- 抽奖模块 -->
        <div id="sudoku_container" class="sudoku_container">
          <div id="prize_box" class="prize_box"></div>
          <div id="sudoku_btn" class="row_gift">
            <img
              id="sudoku_btn_img"
              src="//s-sdk.szmengqukj.com/web/squeeze/img24_24/Lottery-button1.png"
            />
          </div>
        </div>

        <!-- 活动说明 -->
        <div id="rule-box" class="activity-desc">
          <div class="activity-desc-title">
            <img
              src="//s-sdk.szmengqukj.com/web/squeeze/activity-left-dot@2x.png"
            />
            <div>活动说明</div>
            <img
              src="//s-sdk.szmengqukj.com/web/squeeze/activity-right-dot@2x.png"
            />
          </div>
          <div id="activity-desc-content" class="activity-desc-content"></div>
        </div>
      </div>

      <!-- 遮罩层 -->
      <div id="mark" class="mark"></div>

      <!-- 中奖弹窗 -->
      <div id="mark-box" class="mark-box">
        <img
          class="mark-box-1 mark-position"
          src="//s-sdk.szmengqukj.com/web/squeeze/img24_24/Winning-Popup.png"
        />
        <div class="mark-content mark-position">
          <img
            class="mark-box-2"
            src="//s-sdk.szmengqukj.com/web/squeeze/img24_24/Winning-window1.png"
          />
          <img id="prize-img" class="mark-prize" src="" />
          <div id="prize-countdown" class="mark-prize-countdown">
            00:59:30内有效
          </div>
          <div id="prize-name" class="mark-prize-name"></div>
        </div>
        <div class="mark-go">
          <img
            class="mark-box-3"
            src="//s-sdk.szmengqukj.com/web/squeeze/img24_24/Claim-button.png"
          />
          <div class="mark-go-text">
            立即打开APP参与活动
            <img src="//s-sdk.szmengqukj.com/web/squeeze/icon-next@2x.png" />
          </div>
        </div>
      </div>

      <!-- 返回弹窗 -->
      <div id="back-box" class="back-box">
        <img
          class="back-box-1 back-position"
          src="//s-sdk.szmengqukj.com/web/squeeze/new-popup.png"
        />
        <img id="back-prize-img" class="back-prize" src="" />
        <div id="back-name" class="back-prize-name"></div>
        <div id="click-down" class="click-down"></div>
        <div id="close-back-box" class="close-back-box">×</div>
      </div>
    </div>
  </body>
  <script>
    let time = 1;
    let timer = null;
    let drawTimer = null; // 启动抽奖定时器
    const sequenceIds = [0, 1, 2, 4, 7, 6, 5, 3];//抽奖闪烁顺序

    const body = $("body");
    const prize = $("#prize_box"); // 奖品dom
    const lowerBox = $("#rule-box"); // 下盒子

    const mark = $("#mark"); // 遮罩层
    const markBox = $("#mark-box"); // 中奖内容
    const prizeImg = $("#prize-img"); // 中奖图片
    const prizeName = $("#prize-name"); // 中奖名字
    const countdown = $("#prize-countdown"); // 倒计时

    const swiperItem = $("#swiper-item"); // swiper元素
    const activityDesc = $("#activity-desc-content"); // swiper元素

    const backBox = $("#back-box"); // 返回弹窗
    const backPrizeImg = $("#back-prize-img"); // 返回弹窗，中奖图片
    const backName = $("#back-name");
    const clickDown = $("#click-down");
    const closeBackbox = $("#close-back-box");

    // 抽奖按钮
    const prizeStart = $("#sudoku_btn");
    const prizeBtnImg = $("#sudoku_btn_img");

    var resources = `[[${vo.resourcesJson}]]`; // 抽奖九宫格数据
    resources = JSON.parse(resources.replaceAll('&quot;', '"'));
    var channelSaleRecordId = [[${vo.record.channelSaleRecordId}]];
    var urlType = [[${vo.record.urlType}]];
    var platformType = [[${vo.record.platformType}]];
    var apkUrl = `[[${vo.record.apkUrl}]]`;
    var iosUrl = `[[${vo.record.iosUrl}]]`;
    iosUrl = iosUrl.replaceAll('&amp;', '&');
    var uuid = `[[${vo.record.uuid}]]`;
    var isAutoDownload = [[${vo.template.isAutoDownload}]];
    var downloadDelayTime = [[${vo.template.downloadDelayTime}]];
    var isShow = [[${vo.template.isShow}]]; // 是否展示规则
    var carousels = `[[${vo.carousels}]]`; // 轮播内容
    carousels = carousels.slice(1, carousels.length - 1).split(',')
    var templateExtData = `[[${vo.templateExtData}]]`; // 六要素
    var activityRule = `[[${vo.template.activityRule}]]`
    activityRule = activityRule.replaceAll('&quot;', '"').replaceAll('&lt;', '<').replaceAll('&gt;', '>')
    activityDesc.html(activityRule)

    // 获取六要素span
    const devSapn = $("#developer-span"); // 开发者
    const developerSpan = $(".developer-span"); // 开发者
    const authSpan = $("#app-auth-span"); // 应用权限
    const appAuthSpan = $(".app-auth-span"); // 应用权限
    const privacy = $("#privacy-span"); // 隐私政策
    const privacySpan = $(".privacy-span"); // 隐私政策
    const appName = $("#app-name-span"); // 应用名称
    const appNameSpan = $(".app-name-span"); // 应用名称
    const appVersion = $("#app-version-span"); // 应用版本
    const appVersionSpan = $(".app-version-span"); // 应用版本
    const appTime = $("#app-time-span"); // 更新时间
    const appTimeSpan = $(".app-time-span"); // 更新时间

    var lysTopData = formatTemplateExtData(templateExtData);
    if (lysTopData.owmCompanyName) {
      devSapn.html("开发者：" + lysTopData.owmCompanyName);
    }
    if (lysTopData.userRightUrls) {
      authSpan.attr("href", lysTopData.userRightUrls);
    }
    if (lysTopData.privacyAgreementUrls) {
      privacy.attr("href", lysTopData.privacyAgreementUrls);
    }
    if (lysTopData.appName) {
      appName.html(lysTopData.appName);
    }
    if (lysTopData.version) {
      appVersion.html("应用版本：" + lysTopData.version);
    }
    if (lysTopData.date) {
      appTime.html("更新时间：" + lysTopData.date);
    }

    // 隐藏六要素
    if (!lysTopData.owmCompanyName) {
      developerSpan.hide();
    } else {
      developerSpan.show();
    }
    if (!lysTopData.userRightUrls) {
      appAuthSpan.hide();
    } else {
      appAuthSpan.show();
    }
    if (!lysTopData.privacyAgreementUrls) {
      privacySpan.hide();
    } else {
      privacySpan.show();
    }
    if (!lysTopData.appName) {
      appNameSpan.hide();
    } else {
      appNameSpan.show();
    }
    if (!lysTopData.version) {
      appVersionSpan.hide();
    } else {
      appVersionSpan.show();
    }
    if (!lysTopData.date) {
      appTimeSpan.hide();
    } else {
      appTimeSpan.show();
    }

    function formatTemplateExtData(str) {
      let obj = {};
      let strArr = str
        .slice(1, str.length - 1)
        .replaceAll(" ", "")
        .split(",");
      for (const i of strArr) {
        let arr = i.split("=");
        obj[arr[0]] = arr[1];
      }
      return obj;
    }

    function getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
      return null;
    }
    var paramValue = getUrlParam("channelSaleRecordId");

    $(function () {
      $.post(
        "/report/show",
        { channelSaleRecordId: channelSaleRecordId, udid: uuid },
        function (data) {
          if (data.code == 0) {
            console.log("report show count success");
          } else {
            console.log("report show count fail");
          }
        }
      );
      if (isAutoDownload == 1) {
        var u = navigator.userAgent;
        var isiOS =
          !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ||
          !!u.match(/\(M[^;]+;( U;)? Intel.+Mac OS X/);
        if (platformType == 1 || (platformType == 3 && !isiOS)) {
          setTimeout("auto_down()", downloadDelayTime * 1000);
        }
      }
    });

    $(function () {
      pushHistory();

      window.addEventListener(
        "popstate",
        function (e) {
          prizeBtnImg.attr(
            "src",
            "//s-sdk.szmengqukj.com/web/squeeze/img24_24/Lottery-button1.png"
          );
          mark.show();
          markBox.hide();

          if (drawTimer < 94) {
            backBox.addClass("animate__animated animate__zoomIn");
          } else {
            backBox.addClass("animate__animated animate__zoomIn");
          }
          backBox.show();

          window.history.replaceState(
            null,
            null,
            `/main?channelSaleRecordId=${paramValue}`
          );
        },
        false
      );

      function pushHistory() {
        const state = { title: "title", url: "#" };
        window.history.pushState(state, "title", "#");

        const item = resources.find((item) => item.isAward);
        backPrizeImg.attr("src", item.imageUrl);
        backName.html(item.imageName);
      }
    });

    mark.hide();
    markBox.hide();
    backBox.hide();

    if (isShow == 0) {
      lowerBox.hide();
    } else {
      lowerBox.show();
    }


    //奖品列表
    resources && resources.map((item) => (item.active = false));
    resources.push({
      imageOrder: 9,
      isAward: false,
      imageName: "",
      imageUrl: "",
    });

    function sortPrize(list) {
      let node = "";
      list.forEach((item, index) => {
        if (item.imageOrder === 9) {
          node += `<div id="prize_${item.imageOrder - 1}"></div>`;
        } else {
          node += `
            <div id="prize_${item.imageOrder - 1}" class="row_gift" prize="${item.imageOrder - 1}">
              <img id="prize-img_${item.imageOrder}" src="${item.imageUrl}" />
              <div>${item.imageName}</div>
            </div>
          `;
        }
      });
      prize.append(node);
    }

    let arr = resources.slice(3, 5);
    arr.splice(1, 0, resources[resources.length - 1]);
    sortPrize(resources.slice(0, 3));
    sortPrize(arr);
    sortPrize(resources.slice(5, 8));

    function rightSpeed(id) {
      if ([3, 5].includes(id)) {
        return 3;
      } else if ([2, 4, 6, 7].includes(id)) {
        return 7;
      } else {
        return 10;
      }
    }

    /**
     * 抽奖过程动画
     * @param {number} index
     * @param {number} speed 速度
     * @return {void}
     */
    function luckyAnimation(index = 0, speed = 1) {
      let isfun = false;
      time > 8 ? (time += 10) : (time += 0.1);
      time > 40 && (isfun = true);

      setTimeout(() => {
        if (index === 0) {
          resources[sequenceIds[sequenceIds.length - 1]].active = false;
        } else {
          resources[sequenceIds[index - 1]].active = false;
        }

        resources[sequenceIds[index]].active = true;

        resources.forEach((item) => {
          const prizeDom = $(`#prize_${item.imageOrder - 1}`);
          if (item.active) {
            prizeDom.addClass("row_gift_isactive");
          } else {
            prizeDom.removeClass("row_gift_isactive");
          }
        });

        console.log(resources[sequenceIds[index]]);
        if (isfun && resources[sequenceIds[index]].isAward) {
          //动画结束,发送弹窗事件
          timer = setTimeout(() => {
            const prizeItem = resources.find((item) => item.isAward == true);
            prizeImg.attr("src", prizeItem.imageUrl);
            prizeName.html(prizeItem.imageName);
            resources[sequenceIds[index]].active = false;
            prizeBtnImg.attr(
              "src",
              "//s-sdk.szmengqukj.com/web/squeeze/lottery-btn2@2x.png"
            );

            mark.show();
            markBox.addClass("animate__animated animate__zoomIn");
            markBox.show();
            backBox.hide();

            countdownTask(3600);
            document.body.style.overflow = "hidden";
          }, 500);

          time = 1;
          isfun = false;
          return;
        }

        index++;
        if (index > 7) index = 0;
        luckyAnimation(index, time);
      }, rightSpeed(resources.find(item => item.isAward).id) * speed);
    }

    prizeStart.click((e) => {
      clearTimeout(timer);
      prizeBtnImg.attr(
        "src",
        "//s-sdk.szmengqukj.com/web/squeeze/img24_24/lotterying2.png"
      );
      luckyAnimation(0, time);
    });

    // 渲染轮播内容
    carousels &&
      carousels.length &&
      carousels.forEach((item) => {
        let node = `
          <div class="swiper-slide">
            <img src="//s-sdk.szmengqukj.com/web/squeeze/icon-notice@2x.png" />
            <span class="swiper-slide-text1">${item}</span>
          </div>
        `;
        swiperItem.append(node);
      });

    // 轮播内容
    var swiper = new Swiper(".mySwiper", {
      direction: "vertical",
      loop: true, // 循环模式选项
      autoplay: {
        delay: 1000,
        stopOnLastSlide: false,
        disableOnInteraction: false,
      },
    });

    /**
     * 渲染倒计时
     * @param {number} downTime 倒计时秒
     * @return {void}
     */
    function countdownTask(downTime) {
      if (downTime === 0) {
        countdown.html("已失效");
        return;
      }
      // 计算剩余时间的小时、分钟和秒数
      var hours = Math.floor((downTime % (60 * 60 * 24)) / (60 * 60));
      var minutes = Math.floor((downTime % (60 * 60)) / 60);
      var seconds = Math.floor(downTime % 60);

      // 更新倒计时显示
      countdown.html(hours + ":" + minutes + ":" + seconds + "内有效");
      setTimeout(() => {
        countdownTask(downTime - 1);
      }, 1000);
    }

    // 点击遮罩层 下载
    mark.click((e) => {
      report_click(channelSaleRecordId, "ARTIFICIAL_CLICK");
      down();
    });

    function auto_down() {
      report_click(channelSaleRecordId, "AUTO_CLICK");
      down();
    }

    // 点击奖品 下载
    markBox.click((e) => {
      report_click(channelSaleRecordId, "ARTIFICIAL_CLICK");
      down();
    });

    clickDown.click((e) => {
      report_click(channelSaleRecordId, "ARTIFICIAL_CLICK");
      down();
    });

    function report_click(channelSaleRecordId, clickType) {
      $.post(
        "/report/click",
        {
          channelSaleRecordId: channelSaleRecordId,
          clickType: clickType,
          udid: uuid,
        },
        function (data) {
          if (data.code === 0) {
            console.log("report click count success");
          } else {
            console.log("report click count fail");
          }
        }
      );
    }

    function down() {
      if (platformType == 1) {
        if (is_weixin()) {
          document.getElementById("androidGuideDiv").style.display = "block";
          return;
        }
        window.location.href = apkUrl;
        return;
      }
      if (platformType == 2) {
        if (is_weixin() && urlType == 1) {
          document.getElementById("iosGuideDiv").style.display = "block";
          return;
        }
        window.location.href = iosUrl;
        return;
      }
      if (platformType == 3) {
        var u = navigator.userAgent;
        var isiOS =
          !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ||
          !!u.match(/\(M[^;]+;( U;)? Intel.+Mac OS X/); //ios终端
        if (isiOS) {
          if (is_weixin() && urlType == 1) {
            document.getElementById("iosGuideDiv").style.display = "block";
            return;
          }
          window.location.href = iosUrl;
          return;
        } else {
          if (is_weixin()) {
            document.getElementById("androidGuideDiv").style.display = "block";
            return;
          }
          window.location.href = apkUrl;
          return;
        }
      }
    }

    function is_weixin() {
      var ua = navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
      }
      return false;
    }

    closeBackbox.click((e) => {
      backBox.hide();
      mark.hide();
    });
  </script>
</html>
